#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
事件管理器
用于处理游戏内事件的订阅和发布
"""

from typing import Dict, List, Callable, Any

class EventManager:
    """事件管理器"""
    
    def __init__(self):
        self.listeners: Dict[str, List[Callable]] = {}
    
    def add_listener(self, event_name: str, callback: Callable):
        """添加事件监听器"""
        if event_name not in self.listeners:
            self.listeners[event_name] = []
        self.listeners[event_name].append(callback)
    
    def remove_listener(self, event_name: str, callback: Callable):
        """移除事件监听器"""
        if event_name in self.listeners:
            try:
                self.listeners[event_name].remove(callback)
            except ValueError:
                pass  # 回调不在列表中
    
    def trigger_event(self, event_name: str, *args, **kwargs):
        """触发事件"""
        if event_name in self.listeners:
            for callback in self.listeners[event_name][:]:  # 复制列表避免修改时出错
                try:
                    callback(*args, **kwargs)
                except Exception as e:
                    print(f"事件回调执行失败 {event_name}: {e}")
    
    def clear_listeners(self, event_name: str = None):
        """清空监听器"""
        if event_name:
            if event_name in self.listeners:
                self.listeners[event_name].clear()
        else:
            self.listeners.clear()